/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.FAQ;
import org.hibernate.Session;
import service.FAQDao;
import service.HibernateUtil;

/**
 *
 * @author kjeld
 */
public class FAQController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        long userID = 0;
        boolean admin = false;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals("status")) {
                if (cookie.getValue().equals("Admin")) {
                    admin = true;
                }
            } else if (cookie.getName().equals("userID")) {
                userID = Long.parseLong(cookie.getValue());
            }
        }
        HttpSession session = request.getSession(true);
        HibernateUtil HU = new HibernateUtil();
        Session sessie = HU.openSession();
        FAQDao fdao = new FAQDao(sessie);
        List<FAQ> faqs = fdao.findAll();
        session.setAttribute("faqs", faqs);
        if (admin == true) {
            session.setAttribute("admin", "" + admin);
        } else {
            session.setAttribute("admin", null);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher("faq.jsp");
        dispatcher.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        HibernateUtil HU = new HibernateUtil();
        Session sessie = HU.openSession();
        FAQDao fdao = new FAQDao(sessie);
        try {
            FAQ faq = fdao.get(Long.parseLong(request.getParameter("questionID")));
            fdao.delete(faq);
        } catch (Exception ex) {
            System.out.println("Exception: " + ex);
        }
        response.sendRedirect("faq");
    }
}
